package org.springframework.samples.petclinic.web

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.samples.petclinic.Clinic
import org.springframework.samples.petclinic.Pet
import org.springframework.samples.petclinic.Visit
import org.springframework.samples.petclinic.validation.VisitValidator
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.SessionAttributes
import org.springframework.web.bind.annotation.InitBinder
import org.springframework.web.bind.support.SessionStatus
import org.springframework.web.bind.WebDataBinder

@Controller
@RequestMapping(Array("/addVisit.do"))
@SessionAttributes(Array("visit"))
class AddVisitForm {
  
  private var clinic:Clinic = null

  @Autowired 
  def setClinic(clinic:Clinic) = {
    this.clinic = clinic
  }

  @InitBinder
  def setAllowedFields(dataBinder:WebDataBinder) = dataBinder.setDisallowedFields(Array("id"))

  @RequestMapping {val method = Array(RequestMethod.GET)}
  def setupForm(@RequestParam("petId") petId:Int, model:Model):String = {
    val pet = this.clinic.loadPet(petId)
    val visit = new Visit()
    pet.addVisit(visit)
    model.addAttribute("visit", visit)
    return "visitForm"
  }
  
  @RequestMapping {val method = Array(RequestMethod.POST)}
  def processSubmit(@ModelAttribute("visit") visit:Visit, result:BindingResult, status:SessionStatus):String = {
    new VisitValidator().validate(visit, result)
    if (result.hasErrors()) {
      return "visitForm"
    } else {
      this.clinic.storeVisit(visit)
      status.setComplete()
      return "redirect:owner.do?ownerId=" + visit.pet.owner.id
    }
  }

}
